import binascii
import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy


class Device:
    def __init__(self, device_name: str, platform_version: str) -> None:
        """
        封装健康云操作
        device_name: 设备号。连接到手机后，可以使用adb devices查看
        platform_version：Android版本号
        """
        cap_dict = dict(
            platformName='Android',
            platformVersion=platform_version,
            automationName='UiAutomator2',
            deviceName=device_name,
            appPackage="com.wondersgroup.hs.healthcloud.patient",
            appActivity=".module.MainActivity",
            skipDeviceInitialization=True,
            skipServerInstallation=True,
            noReset=True,
        )

        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', cap_dict)
        self.driver.update_settings({"waitForIdleTimeout": 300})

        self.protocol_info_checked = False

    def enter_register_ui(self):
        # 进入主页
        self.driver.launch_app()

        # 点击 核酸检测服务
        time.sleep(2.0) # sleep是为了等控件加载完毕，有改进空间
        xpath = "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.FrameLayout/android.widget.FrameLayout/androidx.viewpager.widget.ViewPager/android.widget.RelativeLayout/android.widget.LinearLayout[1]/androidx.recyclerview.widget.RecyclerView/android.widget.LinearLayout[2]/androidx.viewpager.widget.ViewPager/android.widget.RelativeLayout/android.widget.RelativeLayout/androidx.recyclerview.widget.RecyclerView/android.widget.RelativeLayout[2]/android.widget.LinearLayout"
        el = self.driver.find_element(by=AppiumBy.XPATH, value=xpath)
        el.click()

        # 点击 立即登记
        time.sleep(1.0)
        selector = 'new UiSelector().text("立即登记")'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.click()

    def register_info(self, id_no: str, name: str, phone_no: str, address: str, company: str) -> bool:
        time.sleep(1.0)
        selector = 'new UiSelector().className("android.view.View").enabled(true).instance(3)'
        info_board = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)


        # 选择 非本人
        selector = 'new UiSelector().className("android.view.View").enabled(true).instance(11)'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.click()

        # 输入 身份证号
        selector = 'new UiSelector().className("android.widget.EditText").enabled(true).instance(0)'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.set_text(id_no)

        # 输入 姓名
        selector = 'new UiSelector().className("android.widget.EditText").enabled(true).instance(1)'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.set_text(name)

        # 性别和生日App会根据身份证自动填上，略

        # 输入 手机号码
        selector = 'new UiSelector().className("android.widget.EditText").enabled(true).instance(3)'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.set_text(phone_no)

        # 输入 地址
        selector = 'new UiSelector().className("android.widget.EditText").enabled(true).instance(4)'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.set_text(address)

        # 点击 所在单位
        el = select_child_by_class(info_board, 'android.view.View', 41) #self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.click()
        # 输入： 单位
        selector = 'new UiSelector().className("android.widget.EditText").enabled(true).instance(0)'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.set_text(company)

        # 点击：确定
        # time.sleep(1.0)
        selector = 'new UiSelector().className("android.view.View").enabled(true).instance(2)'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.click()

        # 点击： 勾选已阅读并同意《健康云隐私政策》
        # protocol_info_checked用于记录是否勾选过，如果勾选过，则下次注册时就不用再点击了
        if not self.protocol_info_checked:
            time.sleep(1.0)
            xpath = "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.LinearLayout/android.webkit.WebView/android.webkit.WebView/android.view.View[3]/android.view.View[1]/android.view.View[1]"
            el = self.driver.find_element(by=AppiumBy.XPATH, value=xpath)
            el.click()
            self.protocol_info_checked = True
        
        # 点击：登记
        time.sleep(1.0) # 此处sleep应该可以去掉
        selector = 'new UiSelector().text("登记")'
        el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
        el.click()


        # 等待注册完
        time.sleep(5.0)
        # 同感匹配“登记成功”判断是否成功
        selector = 'new UiSelector().textContains("登记成功")'
        try:
            el = self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)
            print('登记成功')
        except Exception as e:
            print('登记失败')
            return False

        # 返回
        el = self.driver.find_element(by=AppiumBy.CLASS_NAME, value='android.widget.Button')
        el.click()

        return True
        
    def screenshot(self, path: str):
        screenshotBase64 = self.driver.get_screenshot_as_base64()
        with open(path, 'wb') as f:
            f.write(binascii.a2b_base64(screenshotBase64))

    def close(self):
        self.driver.close_app()


def select_child_by_class(root, classname, index=None):
    if index is None:
        return root.find_element(by=AppiumBy.CLASS_NAME, value=classname)
    else:
        selector = f'new UiSelector().className("{classname}").enabled(true).instance({index})'
        return root.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=selector)